﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Channels;
using System.ServiceModel;

namespace LiveWCFServiceTests
{
    static class TestConfiguration
    {
        const bool UseLiveServices = true;


        const string OnlineRoot = "http://sscc.xe7.co.uk/";
        const string LocalRoot = "http://localhost:53981/";

        const string AccountFile = "C:\\TestSSCCAccount.txt";

        #region Load Service
        static string Root { get { return UseLiveServices?OnlineRoot:LocalRoot; } }
        public static T LoadService<T>(string URI, Func<CustomBinding, EndpointAddress, T> F)
        {
            try
            {
                //Uncomment the next line to force https even when the page browsed to is http (Requires apropriate client access policy).
                //Root = Root.Replace("http://", "https://");
                Uri U = new Uri(new Uri(Root), URI);

                BinaryMessageEncodingBindingElement binary = new BinaryMessageEncodingBindingElement();
                HttpTransportBindingElement transport;
                if (U.Scheme == "http")
                    transport = new HttpTransportBindingElement();
                else if (U.Scheme == "https")
                    transport = new HttpsTransportBindingElement();
                else
                    throw new Exception(U.Scheme + " is not a recognised URI scheme");
                transport.MaxBufferSize = int.MaxValue;
                transport.MaxReceivedMessageSize = transport.MaxBufferSize;
                transport.AllowCookies = true;
                
                CustomBinding binding;
                binding = new CustomBinding(binary, transport);


                EndpointAddress address = new EndpointAddress(U);

                return F(binding, address);
            }
            catch (Exception)
            {
                return default(T);
            }
        }
        #endregion

        #region Load Account Details
        static Lazy<KeyValuePair<string, string>> account = new Lazy<KeyValuePair<string, string>>(() =>
        {
            using (var reader = new System.IO.StreamReader(AccountFile))
            {
                return new KeyValuePair<string, string>(reader.ReadLine(), reader.ReadLine());
            }
        });
        public static string Username { get { return account.Value.Key; } }
        public static string Password { get { return account.Value.Value; } }
        #endregion
    }
}
